<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <title>Wifi Switch</title>
    <link href="__CSS__/bootstrap.css" rel="stylesheet" type="text/css" />
    <link href="__CSS__/font-awesome.css" rel="stylesheet" type="text/css" />
    <link href="__CSS__/layer.css" rel="stylesheet" type="text/css" />
    <link href="__SWITCH__/css/switch.css" rel="stylesheet" type="text/css"/>
    <style>
        .topmargin{
            margin-top: 10px;
            margin-bottom: 20px;
            text-align: center;
        }
        .switchTitle{
            background-color: #337ab7;
            margin: 0px;
            height: 45px;
            line-height: 45px;
            border-top-left-radius: 10px;
            border-top-right-radius: 10px;
            color: white;
        }
        .switchTitle1{
            background-color: gray;
            margin: 0px;
            height: 45px;
            line-height: 45px;
            border-top-left-radius: 10px;
            border-top-right-radius: 10px;
            color: black;
        }
        #basic-addon1,#basic-addon2,#basic-addon3,#basic-addon4,#basic-addon5,#basic-addon6,#basic-addon7,#basic-addon8{
            background-color: #337ab7;
            color: white;
            font-size: 14px;
        }
        #deviceDetialData b{
            font-size: 16px;
        }
    </style>
</head>
<body>
    <!--</nav>-->
    <nav class="navbar navbar-default navbar-fixed-top" style="background-color: #337ab7;">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button style="background-color: #337ab7;" type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only" style="color: white" >Toggle navigation</span>
                    <span class="icon-bar" style="background-color: white"></span>
                    <span class="icon-bar" style="background-color: white"></span>
                    <span class="icon-bar" style="background-color: white"></span>
                </button>
                <a class="navbar-brand" href="#" style="color: white">所有设备</a>
            </div>
            <!--Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav navbar-right">
                    <li><a style="color: white" href="index.html">在线设备</a></li>
                    <li><a style="color: white" href="leave.html">离线设备</a></li>
                    <li  data-toggle="modal" data-target="#myModal2"><a style="color: white" href="#">添加设备</a></li>
                    <li><a style="color: white" href="{:U('User/exitLogin')}">注销登录</a></li>
                </ul>
            </div><!-- /.navbar-collapse -->
        </div><!-- /.container-fluid -->
    </nav>

    <div class="container" style="margin-top: 60px;">
        <div class="row">
            <div class="col-md-12 col-sm-12 col-xs-12" id="deviceContainer">

                <foreach name="info" item="v">
                    <div class="col-md-4 col-sm-6 col-xs-12 topmargin">
                        <section class="main" data-switch-name="{$v.devicebyname}">
                            <script>
                                var timestamp = Date.parse(new Date())/1000;
                                var oldTime = '{$v.isonline}';
                                var isOnline = timestamp - oldTime;
                                var ti = "该设备已离线，请接通电源后再试！";
                                if('{$v.devicebyname}'){
                                    if(isOnline > 60){
                                        document.write('<h3 class="switchTitle1" id="deviceadd">{$v.devicebyname}</h3>');
                                    }else{
                                        document.write('<h3 class="switchTitle" id="deviceadd">{$v.devicebyname}</h3>');

                                    }
                                }else{
                                    if(isOnline > 60){
                                        document.write('<h3 class="switchTitle1" id="deviceadd">{$v.chipid}</h3>');
                                    }else{
                                        document.write('<h3 class="switchTitle" id="deviceadd">{$v.chipid}</h3>');

                                    }
                                }
                                if(isOnline > 60){
                                    document.write('<div class="switch1 demo5" onclick="alert(ti)"><input type="checkbox" id="{$v.id}">');
                                }else{
                                    document.write('<div class="switch demo4" onclick="sendCommand({$v.id})">');

                                }
                            </script>
                            <!--<div class="switch demo4" onclick="sendCommand('{$v.id}')">-->
                                <script>
                                    if('{$v.devicestate}' == 0){
                                        document.write('<input type="checkbox" id="{$v.id}">');
                                    }else{
                                        document.write('<input type="checkbox" id="{$v.id}" checked>');
                                    }
                                </script>
                                <label><i class='icon-off'></i></label>
                            </div>
                            <button type="button" class="btn btn-success" id="detail" onclick="getDetail('{$v.id}')" data-toggle="modal" data-target="#myModal1">详&nbsp;细</button>&nbsp;
                            <button type="button" class="btn btn-warning" onclick="getEdit('{$v.id}')" data-toggle="modal" data-target="#myModal">编&nbsp;辑</button>
                        </section>
                    </div>
                </foreach>

            </div>
            <!--edit-->
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myModalLabel0">编辑设备信息</h4>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 col-xs-12 topmargin">
                                    <div class="input-group input-group-lg">
                                        <span class="input-group-addon " id="basic-addon1">设备&nbsp;&nbsp;&nbsp;&nbsp;Id</span>
                                        <input id="deviceId" readonly="readonly" type="text" class="form-control" placeholder="设备Id" aria-describedby="basic-addon1">
                                    </div>
                                </div>
                                <div class="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 col-xs-12 topmargin">
                                    <div class="input-group input-group-lg">
                                        <span class="input-group-addon " id="basic-addon2">芯片&nbsp;&nbsp;&nbsp;&nbsp;Id</span>
                                        <input id="chipId" readonly="readonly" type="text" class="form-control" placeholder="芯片Id" aria-describedby="basic-addon1">
                                    </div>
                                </div>
                                <div class="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 col-xs-12 topmargin">
                                    <div class="input-group input-group-lg">
                                        <span class="input-group-addon " id="basic-addon3">设备类型</span>
                                        <input id="deviceType" readonly="readonly" type="text" class="form-control" placeholder="设备类型" aria-describedby="basic-addon1">
                                    </div>
                                </div>
                                <div class="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 col-xs-12 topmargin">
                                    <div class="input-group input-group-lg">
                                        <span class="input-group-addon " id="basic-addon4">设备归属</span>
                                        <input readonly="readonly" id="deviceBelong" type="text" class="form-control" placeholder="设备归属" aria-describedby="basic-addon1">
                                    </div>
                                </div>
                                <div class="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 col-xs-12 topmargin">
                                    <div class="input-group input-group-lg">
                                        <span class="input-group-addon " id="basic-addon5">区域编号</span>
                                        <input id="regionNum" type="text" class="form-control" placeholder="区域编号" aria-describedby="basic-addon1">
                                    </div>
                                </div>
                                <div class="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 col-xs-12 topmargin">
                                    <div class="input-group input-group-lg">
                                        <span class="input-group-addon " id="basic-addon6">楼宇编号</span>
                                        <input id="buildingNum" type="text" class="form-control" placeholder="楼宇编号" aria-describedby="basic-addon1">
                                    </div>
                                </div>
                                <div class="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 col-xs-12 topmargin">
                                    <div class="input-group input-group-lg">
                                        <span class="input-group-addon " id="basic-addon7">设备地址</span>
                                        <input id="deviceAdd" type="text" class="form-control" placeholder="设备地址" aria-describedby="basic-addon1">
                                    </div>
                                </div>
                                <div class="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 col-xs-12 topmargin">
                                    <div class="input-group input-group-lg">
                                        <span class="input-group-addon " id="basic-addon8">设备别名</span>
                                        <input id="deviceByname" type="text" class="form-control" placeholder="设备别名" aria-describedby="basic-addon1">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer" id="operation">
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                            <button type="button" class="btn btn-primary" id="saveInfo" onclick="saveEdit()">保存修改</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--detail-->
            <div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myModalLabel">设备详细数据</h4>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 col-xs-12 topmargin" id="deviceDetialData">

                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        </div>
                    </div>
                </div>
            </div>
            <!--add-->
            <div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" >添加设备</h4>
                        </div>
                        <div class="modal-body">
                            <div class="row">

                                <div class="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 col-xs-12 topmargin">
                                    <div class="input-group input-group-lg">
                                        <span class="input-group-addon " style="background-color: #449d44;color: white">芯片&nbsp;&nbsp;&nbsp;&nbsp;Id</span>
                                        <input id="addId" type="text" class="form-control" placeholder="输入要添加的芯片Id" aria-describedby="basic-addon1">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="addDevice();">添加</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="panel panel-primary" style="margin-top: 100px;">
        <div class="panel-body">
            <p align="center">
                Copyright © 2017.HengChuang Team All rights reserved.Powered by
                <a href="http://115.159.151.135/" target="_blank" title="Xwen">Xwen</a>
            </p>
            <p align="center" style="color: #337ab7">指导老师：罗回彬&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;成员：卢学文&nbsp;&nbsp;黄嘉爔</p>
        </div>
    </div>



</body>
</html>
<script src="__JS__/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="__JS__/bootstrap.js" type="text/javascript"></script>
<script src="__JS__/layer.js" type="text/javascript"></script>
<script>
    function addDevice(){
        var chipID = $("#addId").val();
        var con = confirm("确认添加设备:"+chipID+"？");

        if(con){
            $.ajax({
                url: "{:U('Index/addDevice')}",
                type: "post",
                dataType: "json",
                data: {chipID:chipID},
                success: function(data){
                    var da = eval(data);
                    console.log(da);
                    if(da){
                        alert("已成功添加设备:"+chipID+"！");
                        history.go(0);
                    }else{
                        alert("添加设备:"+chipID+"失败！\n\n原因：该设备不存在或已被添加！");
                    }
                },
//                error:function(){
//
//                }
            })
        }

    }
    function removeDevice(id){
        var con = confirm("确认删除该设备？");
        if(con){
            $.ajax({
                url: "{:U('Index/removeDevice')}",
                type: "post",
                dataType: "json",
                data: {deviceId:id},
                success: function(data){
                    var da = eval(data);
//                    console.log(da);
                    if(da){
                        alert("已成功删除该设备！");
                        history.go(0);
                    }else{
                        alert("删除失败！");
                    }
                }
            })
        }

    }
    function getDetail(id){
//        deviceDetialData
        setInterval(function(){
            $.ajax({
                url: "{:U('Index/getDetail')}",
                type: "post",
                dataType: "json",
                data: {deviceId:id},
                success: function(data){
                    var htmlContent = "";
                    var deviceData = eval("("+data+")");
//                console.log("Ajax successful! deviceData: "+deviceData.length);
//                console.log(deviceData);
                    $.each(deviceData,function(index,item){
                        var time = $.myTime.UnixToDate(deviceData[index]['time'],true);
                    console.log(time);
                        htmlContent += '<div class="panel panel-default"><div class="panel-body">' +
                            time+'  <b>'+deviceData[index]['chipid']+'</b>  '+deviceData[index]['ip']+'  <b>'+deviceData[index]['port']+'</b>  '+deviceData[index]['devicetype']+'  <b>'+deviceData[index]['devicestate'] +
                            '</b></div></div>';
                    });
                    $("#deviceDetialData").html(htmlContent);
                }
            })
        },1000)

    }
    function getEdit(id){

        $("#deviceId").val("");
        $("#chipId").val("");
        $("#deviceType").val("");
        $("#deviceBelong").val("");
        $("#regionNum").val("");
        $("#buildingNum").val("");
        $("#deviceAdd").val("");
        $("#deviceByname").val("");
//        $("#deviceBelong").removeAttr("readonly");
        $("#regionNum").removeAttr("readonly");
        $("#buildingNum").removeAttr("readonly");
        $("#deviceAdd").removeAttr("readonly");
        $("#deviceByname").removeAttr("readonly");
        $.ajax({
            url: "{:U('Index/editInfo')}",
            type: "post",
            dataType: "json",
            data: {deviceId:id},
            success: function(data){
                var deviceData = eval("("+data+")");
                var removeContent = '<button type="button" class="btn btn-warning" onclick="removeDevice('+deviceData['id']+');">删除设备</button>';
//                console.log("Ajax successful! deviceData: "+deviceData.length);
//                console.log(deviceData);
                $("#deviceId").val(deviceData['id']);
                $("#chipId").val(deviceData['chipid']);
                $("#deviceType").val(deviceData['devicetype']);
                $("#deviceBelong").val(deviceData['devicebelong']);
                $("#regionNum").val(deviceData['regionnum']);
                $("#buildingNum").val(deviceData['buildingnum']);
                $("#deviceAdd").val(deviceData['deviceadd']);
                $("#deviceByname").val(deviceData['devicebyname']);
                $("#operation").prepend(removeContent);
            }
        })
    }
    function saveEdit(){
        var deviceId= $("#deviceId").val();
        var chipId= $("#chipId").val();
        var deviceType= $("#deviceType").val();
        var deviceBelong= $("#deviceBelong").val();
        var regionNum= $("#regionNum").val();
        var buildingNum= $("#buildingNum").val();
        var deviceAdd= $("#deviceAdd").val();
        var deviceByname= $("#deviceByname").val();
        $.ajax({
            url: "{:U('Index/saveInfo')}",
            type: "post",
            dataType: "json",
            data: {buildingNum:buildingNum,deviceAdd:deviceAdd,deviceByname:deviceByname,deviceId:deviceId,chipId:chipId,deviceType:deviceType,deviceBelong:deviceBelong,regionNum:regionNum},
            success: function(data){
                var deviceData = eval("("+data+")");
                console.log("Ajax send successful! deviceData: "+deviceData['status']);
                $("#deviceBelong").attr("readonly","readonly");
                $("#regionNum").attr("readonly","readonly");
                $("#buildingNum").attr("readonly","readonly");
                $("#deviceAdd").attr("readonly","readonly");
                $("#deviceByname").attr("readonly","readonly");
                history.go(0);
            }
        })
    }
    $(document).ready(function(){
        setInterval(function(){
            $.ajax({
                type: "POST",
                url: "{:U('Index/allRefresh')}",
                dataType: "json",
                success: function(data){
                    var deviceData = eval("("+data+")");

//                    console.log("Ajax successful! deviceData: "+deviceData.length);
//                    console.log(deviceData);
                    var htmlContent = '';
                    $.each(deviceData,function(index,item){
                        var switchTitle = "";
                        var inputContent = "";
                        var onLineContent = "";
                        var leaveClickContent = "";
                        var ti = "该设备已离线，请接通电源后再试！";
                        var timestamp = Date.parse(new Date())/1000;
                        var oldTime = deviceData[index]['isonline'];
                        var isOnline = timestamp - oldTime;
                        console.log(timestamp);
                        if(deviceData[index]['devicebyname']){
                            switchTitle = deviceData[index]['devicebyname'];
                        }else{
                            switchTitle = deviceData[index]['chipid'];
                        }
                        if(deviceData[index]['devicestate'] == 0){
                            inputContent = '<input type="checkbox" id="'+deviceData[index]['id']+'">';
                        }else{
                            inputContent = '<input type="checkbox" id="'+deviceData[index]['id']+'" checked>';
                        }
                        if(isOnline > 60){
                            onLineContent = '<h3 class="switchTitle1">'+switchTitle+'</h3>';
                        }else{
                            onLineContent = '<h3 class="switchTitle">'+switchTitle+'</h3>';
                        }
                        if(isOnline > 60){
                            leaveClickContent = '<div class="switch1 demo5" onclick="alert(ti)">';
                        }else{
                            leaveClickContent = '<div class="switch demo4" onclick="sendCommand('+deviceData[index]['id']+')">';
                        }
                        htmlContent += '<div class="col-md-4 col-sm-6 col-xs-12 topmargin">' +
                            '                        <section class="main" data-switch-name="'+deviceData[index]['devicebyname']+'">' +onLineContent +
                            leaveClickContent +inputContent+
                            '                            <label><i class=\'icon-off\'></i></label>' +
                            '                        </div>' +
                            '                        <button type="button" class="btn btn-success" onclick="getDetail('+deviceData[index]['id']+')"  data-toggle="modal" data-target="#myModal1">详&nbsp;细</button>' +
                            '                        <button type="button" class="btn btn-warning" onclick="getEdit('+deviceData[index]['id']+')"  data-toggle="modal" data-target="#myModal">编&nbsp;辑</button>' +
                            '                    </section>' +
                            '                </div>';
                    });

                    $("#deviceContainer").empty();
                    $("#deviceContainer").html(htmlContent);
                }
            })
        },10000);
    })
    function sendCommand(switchName){
        var box = document.getElementById(switchName);
        if(box.checked){
            $.ajax({
                type: "POST",
                url: "../../../Console.php?id="+switchName+"&f=0",
                data: {led:"SWITCH1"},
            });
        }else{
            $.ajax({
                type: "POST",
                url: "../../../Console.php?id="+switchName+"&f=0",
                data: {led:"SWITCH0"},
            });
        }
    }

    (function($) {
        $.extend({
            myTime: {
                /**
                 * 当前时间戳
                 * @return <int>    unix时间戳(秒)
                 */
                CurTime: function(){
                    return Date.parse(new Date())/1000;
                },
                /**
                 * 日期 转换为 Unix时间戳
                 * @param <string> 2014-01-01 20:20:20 日期格式
                 *
                 * @return <int>    unix时间戳(秒)
                 */
                DateToUnix: function(string) {
                    var f = string.split(' ', 2);
                    var d = (f[0] ? f[0] : '').split('-', 3);
                    var t = (f[1] ? f[1] : '').split(':', 3);
                    return (new Date(
                        parseInt(d[0], 10) || null,
                        (parseInt(d[1], 10) || 1) - 1,
                        parseInt(d[2], 10) || null,
                        parseInt(t[0], 10) || null,
                        parseInt(t[1], 10) || null,
                        parseInt(t[2], 10) || null
                    )).getTime() / 1000;
                },
                /**
                 * 时间戳转换日期
                 * @param <int> unixTime  待时间戳(秒)
                 * @param <bool> isFull  返回完整时间(Y-m-d 或者 Y-m-d H:i:s)
                 * @param <int> timeZone  时区
                 */
                UnixToDate: function(unixTime, isFull, timeZone) {
                    if (typeof (timeZone) == 'number')
                    {
                        unixTime = parseInt(unixTime) + parseInt(timeZone) * 60 * 60;
                    }
                    var time = new Date(unixTime * 1000);
                    var ymdhis = "";
                    ymdhis += time.getUTCFullYear() + "-";
                    ymdhis += (time.getUTCMonth()+1) + "-";
                    ymdhis += time.getUTCDate();
                    if (isFull === true)
                    {
                        ymdhis += " " + time.getUTCHours() + ":";
                        ymdhis += time.getUTCMinutes() + ":";
                        ymdhis += time.getUTCSeconds();
                    }
                    return ymdhis;
                }
            }
        });
    })(jQuery);

</script>